// 项目数据结构
let projectData = {
    buildings: [
        {
            id: 1,
            name: "1号宿舍楼",
            floors: [
                {
                    id: 101,
                    name: "1层",
                    tasks: [
                        { id: 1001, name: "地基工程", start: "2025-01-01", end: "2025-01-15", progress: 100 },
                        { id: 1002, name: "主体结构", start: "2025-01-16", end: "2025-02-15", progress: 80 },
                        { id: 1003, name: "装修工程", start: "2025-02-16", end: "2025-03-15", progress: 30 },
                        { id: 1004, name: "验收交付", start: "2025-03-16", end: "2025-03-31", progress: 0 }
                    ]
                },
                {
                    id: 102,
                    name: "2层",
                    tasks: [
                        { id: 1005, name: "地基工程", start: "2025-01-05", end: "2025-01-20", progress: 90 },
                        { id: 1006, name: "主体结构", start: "2025-01-21", end: "2025-02-20", progress: 60 },
                        { id: 1007, name: "装修工程", start: "2025-02-21", end: "2025-03-20", progress: 10 },
                        { id: 1008, name: "验收交付", start: "2025-03-21", end: "2025-04-05", progress: 0 }
                    ]
                }
            ]
        },
        {
            id: 2,
            name: "2号宿舍楼",
            floors: [
                {
                    id: 201,
                    name: "1层",
                    tasks: [
                        { id: 2001, name: "地基工程", start: "2025-01-10", end: "2025-01-25", progress: 70 },
                        { id: 2002, name: "主体结构", start: "2025-01-26", end: "2025-02-25", progress: 40 },
                        { id: 2003, name: "装修工程", start: "2025-02-26", end: "2025-03-25", progress: 0 },
                        { id: 2004, name: "验收交付", start: "2025-03-26", end: "2025-04-10", progress: 0 }
                    ]
                }
            ]
        }
    ]
};

// 全局变量
let ganttChart = null;
let currentEditTask = null;
let history = [];

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    renderProjectTree();
    renderGanttChart();
    loadData();
});

// 渲染项目树形结构
function renderProjectTree() {
    const treeContainer = document.getElementById('projectTree');
    treeContainer.innerHTML = '';

    projectData.buildings.forEach(building => {
        // 楼栋
        const buildingDiv = createTreeItem(building.name, 'fas fa-building', 1);
        buildingDiv.onclick = () => selectBuilding(building.id);
        treeContainer.appendChild(buildingDiv);

        // 楼层
        building.floors.forEach(floor => {
            const floorDiv = createTreeItem(floor.name, 'fas fa-layer-group', 2);
            floorDiv.onclick = () => selectFloor(building.id, floor.id);
            treeContainer.appendChild(floorDiv);

            // 工序
            floor.tasks.forEach(task => {
                const taskDiv = createTreeItem(task.name, 'fas fa-hammer', 3);
                taskDiv.onclick = () => selectTask(task.id);
                taskDiv.dataset.taskId = task.id;
                treeContainer.appendChild(taskDiv);
            });
        });
    });
}

// 创建树形项目
function createTreeItem(text, iconClass, level) {
    const div = document.createElement('div');
    div.className = `tree-item level-${level}`;
    div.innerHTML = `<i class="${iconClass}"></i> ${text}`;
    return div;
}

// 渲染甘特图
function renderGanttChart() {
    const ctx = document.getElementById('ganttChart').getContext('2d');
    
    // 收集所有任务
    const allTasks = [];
    projectData.buildings.forEach(building => {
        building.floors.forEach(floor => {
            floor.tasks.forEach(task => {
                allTasks.push({
                    ...task,
                    buildingName: building.name,
                    floorName: floor.name
                });
            });
        });
    });

    // 准备数据
    const labels = allTasks.map(task => `${task.buildingName}-${task.floorName}-${task.name}`);
    const datasets = [{
        label: '施工进度',
        data: allTasks.map(task => ({
            x: [new Date(task.start), new Date(task.end)],
            y: `${task.buildingName}-${task.floorName}-${task.name}`,
            progress: task.progress,
            task: task
        })),
        backgroundColor: allTasks.map(task => {
            if (task.progress === 100) return '#28a745';
            if (task.progress > 0) return '#ffc107';
            return '#dc3545';
        }),
        borderWidth: 1,
        borderColor: '#fff',
        borderRadius: 4
    }];

    // 销毁旧图表
    if (ganttChart) {
        ganttChart.destroy();
    }

    // 创建新图表
    ganttChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: datasets
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const task = context.dataset.data[context.dataIndex].task;
                            return [
                                `工序: ${task.name}`,
                                `开始: ${task.start}`,
                                `结束: ${task.end}`,
                                `进度: ${task.progress}%`
                            ];
                        }
                    }
                }
            },
            scales: {
                x: {
                    type: 'time',
                    time: {
                        unit: 'day',
                        displayFormats: {
                            day: 'MM-dd'
                        }
                    },
                    title: {
                        display: true,
                        text: '日期'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: '施工工序'
                    }
                }
            },
            onClick: (event, elements) => {
                if (elements.length > 0) {
                    const index = elements[0].index;
                    const task = datasets[0].data[index].task;
                    openEditModal(task);
                }
            }
        }
    });
}

// 打开编辑模态框
function openEditModal(task) {
    currentEditTask = task;
    document.getElementById('taskName').value = task.name;
    document.getElementById('startDate').value = task.start;
    document.getElementById('endDate').value = task.end;
    
    const modal = new bootstrap.Modal(document.getElementById('editModal'));
    modal.show();
}

// 更新任务
function updateTask() {
    if (!currentEditTask) return;

    const newStart = document.getElementById('startDate').value;
    const newEnd = document.getElementById('endDate').value;

    if (new Date(newStart) >= new Date(newEnd)) {
        alert('开始日期必须早于结束日期');
        return;
    }

    // 保存历史
    history.push(JSON.parse(JSON.stringify(projectData)));

    // 更新任务
    projectData.buildings.forEach(building => {
        building.floors.forEach(floor => {
            const task = floor.tasks.find(t => t.id === currentEditTask.id);
            if (task) {
                task.start = newStart;
                task.end = newEnd;
            }
        });
    });

    // 重新渲染
    renderGanttChart();
    saveData();

    // 关闭模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('editModal'));
    modal.hide();
}

// 撤销更改
function undoChange() {
    if (history.length > 0) {
        projectData = history.pop();
        renderProjectTree();
        renderGanttChart();
        saveData();
    }
}

// 保存数据到服务器
async function saveData() {
    try {
        const response = await fetch('/api/save', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(projectData)
        });
        
        if (!response.ok) {
            throw new Error('保存失败');
        }
        
        console.log('数据已保存');
    } catch (error) {
        console.error('保存失败:', error);
        // 本地存储作为后备
        localStorage.setItem('ganttData', JSON.stringify(projectData));
    }
}

// 加载数据
async function loadData() {
    try {
        const response = await fetch('/api/load');
        if (response.ok) {
            const data = await response.json();
            if (data && data.buildings) {
                projectData = data;
                renderProjectTree();
                renderGanttChart();
            }
        }
    } catch (error) {
        console.error('从服务器加载失败:', error);
        // 尝试从本地存储加载
        const savedData = localStorage.getItem('ganttData');
        if (savedData) {
            projectData = JSON.parse(savedData);
            renderProjectTree();
            renderGanttChart();
        }
    }
}

// 导出PNG
function exportToPNG() {
    const canvas = document.getElementById('ganttChart');
    const link = document.createElement('a');
    link.download = '宿舍楼施工工期图.png';
    link.href = canvas.toDataURL();
    link.click();
}

// 导出PDF
function exportToPDF() {
    const { jsPDF } = window.jspdf;
    const canvas = document.getElementById('ganttChart');
    const imgData = canvas.toDataURL('image/png');
    
    const pdf = new jsPDF('l', 'mm', 'a4');
    const imgWidth = 280;
    const imgHeight = (canvas.height * imgWidth) / canvas.width;
    
    pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight);
    pdf.save('宿舍楼施工工期图.pdf');
}

// 选择功能
function selectBuilding(buildingId) {
    console.log('选择楼栋:', buildingId);
}

function selectFloor(buildingId, floorId) {
    console.log('选择楼层:', buildingId, floorId);
}

function selectTask(taskId) {
    console.log('选择任务:', taskId);
}